﻿
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using NetflixMovieService;

namespace NetflixFormsApplication.Presentors
{
    internal class MovieSearchPresenter
    {
        private readonly IMovieSearchView _view;
        private readonly IMovieService _netflixService;
        private const int _numberOfGridColumns = 7;

        public int NumberOfGridColumns 
        {
            get { return _numberOfGridColumns; }
        }

        public MovieSearchPresenter(IMovieSearchView view, IMovieService netflixService)
        {
            _view = view;
            _netflixService = netflixService;
        }

        public IEnumerable<ImageEntity> RetrieveMovies(string releaseYear, string maxResultSet)
        {
            int releaseYearNumber, maxResults;

            _view.ClearView();
            
            // Parse the inputs
            Int32.TryParse(maxResultSet, out maxResults);
            if (Int32.TryParse(releaseYear, out releaseYearNumber))
                return _netflixService.GetMovieBoxArtByReleaseYear(releaseYearNumber, maxResults);

            return Enumerable.Empty<ImageEntity>();
        }

        // Method only used for the form UI since it relies on a DataGridView to display
        public void UpdateFormDataGridView(IEnumerable<ImageEntity> movieArtCollection)
        {
            int counter = 0, movieCounter = 0, totalMovieCount = movieArtCollection.Count();

            if (movieArtCollection == null || totalMovieCount == 0)
                return;

            // Add the image columns
            DataGridViewRow viewRow = null;

            foreach (var movieArtUrl in movieArtCollection)
            {
                Image boxArt;
                try
                {
                    boxArt = MovieArtUtility.CreateMovieImageFromUrl(movieArtUrl.ImagePath);
                }
                catch (Exception ex)
                {
                    _view.SendMessage("Warning:  Not all movie art could be loaded");
                    continue;
                }

                if (counter == 0)
                    viewRow = new DataGridViewRow();

                if (boxArt != null)
                {
                    DataGridViewImageCell cell = new DataGridViewImageCell();
                    cell.Value = boxArt;
                    viewRow.Cells.Add(cell);
                    counter++;
                    movieCounter++;

                    // Add row to gridview once we've added all the cells
                    if (counter == NumberOfGridColumns || movieCounter == totalMovieCount)
                    {
                        _view.AddGridRow(viewRow);
                        counter = 0;
                    }
                }
            }
        }

    }
}
